import { reactive } from 'vue'
import { deepCopyObject, hasOwnProp } from '../utils/normalUtils'
import { sendServiceData } from '../service'


export interface IPageData {
    isLoading: boolean,
    dataSource: any [],
    total: number,
    pageSizeList: number[],

    length: number,
    pageIndex: number,
    catchSend:any,
    [props:string]:any
}

/**
 * 分页查询模型 简单写 不整体封装了
 */
export class PageQuery {
    // 查询方法
    queryMethod:any = null

    queryHandler:any = null

    resultListHandler:any = null

    resultItemHandler:any = null

    listField = 'rows'

    totalField = 'total'

    /**
     * 发送参数的 num 字段
     */
    pageNumField = 'pageNum'// pageIndex

    /**
     * 发送参数的 每页数量字段
     */
    pageSizeField = 'pageSize'// length

    /**
     * 所有处理完回调函数 fixed
     */
    endHandler:any = null

    pageData:IPageData = reactive({
        isLoading: false,
        dataSource: [],
        total: 1,
        pageSizeList: [20, 30, 50, 100, 150, 200],

        length: 30,
        pageIndex: 1,
        catchSend: null
    })

    search = null

    catchSend:any = null

    catchMode = false

    hasLast = false

    // 优先清理数据
    firstClear = false

    /**
     * 自动追加下标
     */
    autoIndex = false
    /**
     * 下标字段
     */
    autoIndexField = '$index'

    constructor(options:any = null) {
        if (options) {
            this.queryMethod = options.queryMethod || null
            this.queryHandler = options.queryHandler || null
            this.resultListHandler = options.resultListHandler || null
            this.endHandler = options.endHandler || null
            if (options.search) this.search = options.search
            if (hasOwnProp(options, 'catchMode')) this.catchMode = options.catchMode
            if (hasOwnProp(options, 'pageData'))Object.assign(this.pageData, options.pageData || {})
            if (hasOwnProp(options, 'autoIndex')) this.autoIndex = options.autoIndex
            if (hasOwnProp(options, 'autoIndexField')) this.autoIndexField = options.autoIndexField
        }
    }

    /**
     * 查列表
     * @param params
     * @param resultHandler
     * @param itemHandler
     * @param endHandler
     */
    async queryList(params:any = null, resultHandler:any = null, itemHandler:any = null, endHandler:any = null) {
        if (resultHandler) this.resultListHandler = resultHandler
        if (itemHandler) this.resultItemHandler = itemHandler
        if (endHandler) this.endHandler = endHandler
        this.hasLast = false
        this.pageData.pageIndex = 1
        this.pageData.total = 0
        if (this.firstClear) this.pageData.dataSource = []
        await this.executeQuery(params, true)
        return this.pageData.dataSource || []
    }

    /**
     * 执行查询
     * @param params
     * @param reset
     */
    async executeQuery(params:any, reset = false) {
        this.setCatchSend(params ? deepCopyObject(params) : deepCopyObject(this.search || {}))
        this.catchSend[this.pageSizeField] = this.pageData.length
        this.catchSend[this.pageNumField] = this.pageData.pageIndex
        if (this.queryHandler) this.setCatchSend(this.queryHandler(this.catchSend))
        let result = await sendServiceData(this.queryMethod, this.catchSend, this.pageData)
        // 分页返回数据 加一层验证
        if (!result) {
            result = {
                [this.totalField]: 0,
                [this.listField]: []
            }
        }
        let list:any[] = []
        if (this.resultListHandler) list = this.resultListHandler(result)
        else list = this.initResultList(result)
        this.hasLast = list.length < this.pageData.index
        if (list && list.length > 0 && (this.resultItemHandler || this.autoIndex)) {
            list.forEach((item, index) => {
                item[this.autoIndexField] = this.countItemIndex(index)
                return this.resultItemHandler ? this.resultItemHandler(item) : item
            })
        }
        if (this.catchMode && !reset) {
            if (!this.pageData.dataSource) this.pageData.dataSource = []
            this.pageData.dataSource.push(...list)
        } else {
            this.pageData.dataSource = list || []
        }
        this.pageData.total = this.initResultTotal(result)
        if (this.endHandler) this.endHandler(this.pageData)
    }

    /**
     * 扩展下
     * @param params
     */
    setCatchSend(params:any) {
        this.catchSend = params
        this.pageData.catchSend = params
    }

    /**
     * 页数变化处理
     */
    async pageChange() {
        this.executeQuery(this.catchSend)
    }

    /**
     * 重新查询
     */
    async reQuery() {
        await this.queryList(this.catchSend)
    }

    /**
     * 下一页
     */
    async next() {
        if (this.hasLast ||
            this.pageData.dataSource.length === 0 ||
            this.pageData.total <= this.pageData.dataSource.length) return
        this.pageData.pageIndex += 1
        await this.executeQuery(this.catchSend)
    }

    /**
     *
     * @param result
     */
    initResultList(result:any) {
        return (result && hasOwnProp(result, this.listField)) ? (result[this.listField] || []) : []
    }

    /**
     *
     * @param result
     */
    initResultTotal(result:any) {
         return (result && hasOwnProp(result, this.totalField)) ? parseInt(result[this.totalField], 10) : 0
    }

    /**
     * 计算元素整体下标
     * @param index
     */
    countItemIndex(index:number) {
        return (this.pageData.pageIndex - 1) * this.pageData.length + index + 1
    }
}

export function usePageQuery(options:any) {
    const query = new PageQuery(options)
    return { pageActions: query, actions: query, pageData: query.pageData, pagePm: query }
}


